
#include <iostream>
#include <cstdlib>
//#include <malloc.h>

#include <cstdio>

using namespace std;

int main(void)
{
	int *p1 = (int*) malloc(sizeof(int));
	*p1 = 1234;
	cout << *p1 << endl;
	free (p1);
	p1 = NULL; // 防止 double free
	free (p1);
	
	int * p2 = new int;   //在c++ 中， new 是运算符
	*p2 = 5678;
	cout << *p2 << endl;
	delete p2;
	p2 = NULL;
	delete p2;

	int * p3 = new int(100);
	cout << *p3 << endl;
	delete p3;
	p3 = NULL;
	
	// 数组
	int * p4 = new int[5];  
	for ( int i = 0; i < 5; ++i)
	{
		p4[i]  = i;
	}

	for ( int i = 0; i < 5; ++i)
	{
		cout << p4[i]  << ' ' ; 
	}
	cout << endl;
	delete[]  p4;
	p4 = NULL;
	
	// 数组初始化	
	int * p5 = new int[5]{100,200,300};  // c++11 特性，  g++ new.cpp  -std=c++11
	for (int i = 0; i < 5; i ++)
	{
		cout << p5[i] << ' ' ;			
	}
	cout << endl;
	delete[] p5;
	p5 = NULL;
	
	/* N维数组就是 N-1维数组的一维数组
	 * N维数组的首地址　就是一个 N-1维数组的指针 
	 */
		
	// 二维数组
	int (*p6)[4] = new int[3][4]{  
				     {11,12,13,14,},
				     {21,22,23,24,},
				     {31,32,33,34,},
				   };
	for (int i = 0; i < 3; ++i){
		for ( int j= 0; j < 4; ++ j)
			cout << p6[i][j] << ' ' ;
		cout << endl;
	}
	delete[] p6;

	// 三维数组
	int (*p7)[3][4] = new int[2][3][4]{
		{  {111,112,113,114},
		   {211,212,213,214},
		   {311,312,313,314},},
		{  {111,112,113,114},
		   {211,212,213,214},
		   {311,312,313,314},}
		};
	for ( int i = 0; i < 2; ++i ){
		for ( int j = 0; j < 3 ; j ++ ){
			for ( int k = 0; k < 4; k ++){
				cout << p7[i][j][k] << ' ' ;
			}
			cout << endl;
		}
	}
	delete[] p7;
	
	//char * p8 = (char *) malloc (0xFFFFFFFF);
	char * p8 = (char *) malloc (0xFFFFFFFF * 2);
	if (!p8)
		perror( "malloc" );
		// malloc: Cannot allocate memory
	
	/* 内存分配失败,new操作符抛出bad_alloc异常 */	
	try{
		cout << "我要分配内存了!" << endl;
		char * p9  = new char[0xFFFFFFFF];
		cout << "分配内存成功了" << endl;
		*p9 = 'A';
		cout << *p9 << endl;
		delete[] p9;
	}
	catch(exception& ex){
		
		cout << "分配内存失败了!" << endl;
		cout <<  ex.what() << endl;
	}
	
	/*定位分配 */
	char c[4];
	int *p = new(c) int(0x12345678);
	printf("%#x, %#x, %#x, %#x \n",
			c[0],c[1],c[2],c[3]); 
	/*
         * 内存池，在已有的内存中，创建对象
	 * */

	return 0;
}



